package com.yang.SpingBoot;


import com.yang.SpingBoot.dao.WeiBoMapper;
import com.yang.SpingBoot.model.WeiBo;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Sort {

    private Logger logger = LoggerFactory.getLogger(Sort.class);

    @Resource
    WeiBoMapper weiBoMapper;

    @Test
    public void test() throws IOException {

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        int total = 3703;

        int pageSize = total / 20 + 1;

        for (int i = 0; i < pageSize; i++) {
            List<WeiBo> weiBoList = weiBoMapper.select(i*20);
            logger.info("开始计算第{}页",i);
            for (WeiBo weiBo : weiBoList) {
                executorService.execute(()->{
                    try {
                        logger.info("计算微博id:{}",weiBo.getId());
                        String content = weiBo.getContent();
                        String sortValue = getSortValue(content);
                        if (StringUtils.isNotEmpty(sortValue)){
                            weiBoMapper.updateSort(weiBo.getId(),sortValue);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

       while (true) {
           if (executorService.isShutdown()) {
               System.out.println("执行完成...");
               break;
           }
           try {
               Thread.sleep(3000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

    }


    public String getSortValue(String content) throws IOException{
        String cmd = "py D://sort.py "+content;
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String value = bufferedReader.readLine();
        if (value.length() > 5){
            value = value.substring(0,5);
        }
        return value;
    }

}




